package com.qidian.zl.paper.util;
import java.sql.Time;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class SessionUtil {
    private static Map<String, Map<String, Object>> sessions = new ConcurrentHashMap<>();
    private static Map<String, Timer> timers = new ConcurrentHashMap<>();

    //获取session
    public static Map<String, Object> getSession(String key){
        if(key !=null && sessions.containsKey(key)){
            Timer timer = timers.get(key);
            if(timer==null){
                timer = new Timer();
            }
            timer.cancel();
            timer = null;
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    sessions.remove(key);
                    Timer tmer = timers.remove(key);
                    tmer.cancel();
                    tmer = null;
                }
            },60*60*30);
            return sessions.get(key);
        }
        Map<String,Object> session = new HashMap<>();
        // 创建一个唯一标志 作为session的id
        String k = UUID.randomUUID().toString().replace("-","");
        session.put("sessionid",k);
        sessions.put(k,session);
        // 添加定时任务
        Timer t = new Timer();
        t.schedule(new TimerTask() {
            @Override
            public void run() {
                sessions.remove(k);
                Timer tmer = timers.remove(k);
                tmer.cancel();
                tmer = null;
            }
        },60*60*30);
        timers.put(k,t);
        return session;
    }
    //清空session
    public static void invalidate(String key){
        sessions.remove(key);
        Timer tmer = timers.remove(key);
        tmer.cancel();
        tmer = null;
    }
    public static void updateTime(String key){
        Timer timer = timers.get(key);
        if(timer!=null){
            timer.cancel();
            timer = null;
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                sessions.remove(key);
                Timer tmer = timers.remove(key);
                tmer.cancel();
                tmer = null;
            }
        },60*60*30);
        timers.put(key,timer);
    };

}


